package com.movecar.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.util.URIUtil;

import android.os.AsyncTask;
import android.util.Log;

public class HttpGetRequestAsyncTask extends AsyncTask<Map<String, String>, Void, String> {
	protected int serviceMsgWhat;
	protected RequestResultCallback requestCallback = null;
	protected String mUrl;
	private String appKey = "539599406";
	private String secret = "2073e5cc84354c63a79d4a0fcd5e9923";

	public HttpGetRequestAsyncTask(RequestResultCallback requestCallback, String mUrl) {
		this.requestCallback = requestCallback;
		this.mUrl = mUrl;
	}

	@Override
	protected String doInBackground(Map<String, String>... params) {
		// TODO Auto-generated method stub
		return doGetServer(params[0]);
	}

	@Override
	protected void onPostExecute(String result) {
		if (result != null) {
			requestCallback.onSuccess(result);
		} else {
			requestCallback.onFail("网络不给力");
		}
	}

	public String doGetServer(Map<String, String> params) {
		String queryString = getQueryString(appKey, secret, params);

		StringBuffer response = new StringBuffer();
		HttpClientParams httpConnectionParams = new HttpClientParams();
		httpConnectionParams.setConnectionManagerTimeout(1000);
		HttpClient client = new HttpClient(httpConnectionParams);
		HttpMethod method = new GetMethod(mUrl);

		try {
			if (queryString != null && !queryString.isEmpty()) {
				// Encode query string with UTF-8
				String encodeQuery = URIUtil.encodeQuery(queryString, "UTF-8");
				Log.e("params", queryString.toString());
				method.setQueryString(encodeQuery);
			}

			client.executeMethod(method);
			BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8"));
			String line = null;
			while ((line = reader.readLine()) != null) {
				response.append(line).append(System.getProperty("line.separator"));
			}
			reader.close();
		} catch (URIException e) {
		} catch (IOException e) {
		} finally {
			method.releaseConnection();
		}
		Log.e("result", response.toString());
		return response.toString();

	}

	/**
	 * 获取请求字符串
	 * 
	 * @param appKey
	 * @param secret
	 * @param paramMap
	 * @return
	 */
	public static String getQueryString(String appKey, String secret, Map<String, String> paramMap) {
		String sign = sign(appKey, secret, paramMap);

		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("appkey=").append(appKey).append("&sign=").append(sign);
		for (Entry<String, String> entry : paramMap.entrySet()) {
			stringBuilder.append('&').append(entry.getKey()).append('=').append(entry.getValue());
		}
		String queryString = stringBuilder.toString();
		return queryString;
	}

	/**
	 * 获取请求字符串，参数值进行UTF-8处理
	 * 
	 * @param appKey
	 * @param secret
	 * @param paramMap
	 * @return
	 */
	public static String getUrlEncodedQueryString(String appKey, String secret, Map<String, String> paramMap) {
		String sign = sign(appKey, secret, paramMap);

		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("appkey=").append(appKey).append("&sign=").append(sign);
		for (Entry<String, String> entry : paramMap.entrySet()) {
			try {
				stringBuilder.append('&').append(entry.getKey()).append('=')
						.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
			} catch (UnsupportedEncodingException e) {
			}
		}
		String queryString = stringBuilder.toString();
		return queryString;
	}

	/**
	 * 签名
	 * 
	 * @param appKey
	 * @param secret
	 * @param paramMap
	 * @return
	 */
	public static String sign(String appKey, String secret, Map<String, String> paramMap) {
		// 参数名排序
		String[] keyArray = paramMap.keySet().toArray(new String[0]);
		Arrays.sort(keyArray);

		// 拼接参数
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(appKey);
		for (String key : keyArray) {
			stringBuilder.append(key).append(paramMap.get(key));
		}

		stringBuilder.append(secret);
		String codes = stringBuilder.toString();

		// SHA-1签名
		// For Android
		String sign = new String(Hex.encodeHex(DigestUtils.sha(codes))).toUpperCase();

		return sign;
	}

}
